<template>
    <div>
        <!-- 添加模块 -->
        <div style="margin-bottom: 10px;">
            <el-input v-model="searchName" style="width: 200px;" placeholder="请输入查询名称" clearable
                @keydown.enter="permissionList" />
            <el-button type="primary" @click="permissionList()" placeholder="请输入查询名称"
                style="margin-left: 5px;">查询</el-button>
            <el-button type="success" @click="handleAdd()">添加权限</el-button>
        </div>

        <!-- 添加弹窗 -->
        <el-dialog v-model="showAddForm" title="添加权限" width="50%">
            <el-form :model="form" label-width="100px">
                <el-form-item label="权限名称">
                    <el-input v-model="form.permName" placeholder="请输入权限名称" />
                </el-form-item>
                <el-form-item label="权限URL">
                    <el-input v-model="form.permUrl" placeholder="请输入权限URL" />
                </el-form-item>
                <el-form-item label="权限备注">
                    <el-input v-model="form.permRemark" placeholder="请输入权限备注" />
                </el-form-item>
                <el-form-item label="权限类型">
                    <el-select v-model="form.permType" placeholder="请选择权限类型">
                        <el-option label="菜单" value="菜单" />
                        <el-option label="按钮" value="按钮" />
                        <el-option label="API" value="API" />
                    </el-select>
                </el-form-item>
            </el-form>
            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="showAddForm = false">取 消</el-button>
                    <el-button type="primary" @click="handleAddSubmit()">确 定</el-button>
                </span>
            </template>
        </el-dialog>

        <!--修改弹窗 -->
        <el-dialog v-model="showEditForm" title="修改权限" width="50%">
            <el-form :model="form" label-width="100px">
                <el-form-item label="权限名称">
                    <el-input v-model="form.permName" placeholder="请输入权限名称" />
                </el-form-item>
                <el-form-item label="权限URL">
                    <el-input v-model="form.permUrl" placeholder="请输入权限URL" />
                </el-form-item>
                <el-form-item label="权限备注">
                    <el-input v-model="form.permRemark" placeholder="请输入权限备注" />
                </el-form-item>
                <el-form-item label="权限类型">
                    <el-select v-model="form.permType" placeholder="请选择权限类型">
                        <el-option label="菜单" value="菜单" />
                        <el-option label="按钮" value="按钮" />
                        <el-option label="API" value="API" />
                    </el-select>
                </el-form-item>
            </el-form>
            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="showEditForm = false">取 消</el-button>
                    <el-button type="primary" @click="handleEditSubmit()">确 定</el-button>
                </span>
            </template>
        </el-dialog>

        <!-- 数据表格 -->
        <el-table :data="tableData" border style="width: 100%" :row-class-name="tableRowClassName">
            <el-table-column prop="permId" label="编号" width="60" />
            <el-table-column prop="permName" label="权限名称" />
            <el-table-column prop="permUrl" label="权限URL">
                <template #default="scope">
                    {{ scope.row.permUrl !== (null || '') ? scope.row.permUrl : '--' }}
                </template>
            </el-table-column>
            <el-table-column prop="permRemark" label="权限备注" />
            <el-table-column prop="permType" label="权限类型" width="60" />
            <el-table-column prop="permCreated" label="创建时间">
                <template #default="scope">
                    {{ formatTime(scope.row.permCreated) }}
                </template>
            </el-table-column>
            <el-table-column label="操作" width="280">
                <template #default="scope">
                    <el-button type="success" @click="handleAdd(scope.row)">添加权限</el-button>
                    <el-button type="primary" @click="handleEdit(scope.row)">编辑</el-button>
                    <el-button v-if="hasDeleteButton" type="danger" @click="handleDelete(scope.row.permId)">删除</el-button>
                </template>
            </el-table-column>
        </el-table>
        <!-- 分页 -->
        <!-- layout:里面的值的顺序就是页面显示顺序 -->
        <div class="demo-pagination-block">
            <el-pagination v-model:current-page="currentPage" v-model:page-size="pageSize" :page-sizes="[5, 10, 20, 50]"
                :size="size" layout="total, sizes, prev, pager, next, jumper" :total="total" @size-change="handleSizeChange"
                @current-change="handleCurrentChange" />
        </div>
    </div>
</template>
    
<script setup lang="ts">
import { ref, onMounted,computed } from 'vue';
import { ElButton, ElTable, ElTableColumn, ElMessage, ElMessageBox } from 'element-plus';
import { permissionListApi, deletePermissionApi, addPermissionApi, updatePermissionApi } from '@/api/api';



//分页参数
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(10)
const size = ref('default')

// 查询权限名称
const searchName = ref('');

// 表格数据
const tableData = ref([]);

// 是否显示添加表单
const showAddForm = ref(false);
const showEditForm = ref(false);

// 权限表单
const form = ref<any>({
    permId: null,
    permName: '',
    permUrl: '',
    permRemark: '',
    permType: '',
    permPid: 0,
});

// 查询权限列表
const permissionList = async () => {
    const response = await permissionListApi({ page: currentPage.value, size: pageSize.value, name: searchName.value });
    console.log('查询权限列表', response);
    if (response.code === 200) {
        tableData.value = response.data.list;
        total.value = response.data.total;
    } else {
        ElMessage.error('查询失败');
    }
};

// 打开新增权限弹窗
const handleAdd = (row?: any) => {
    form.value = {
        permId: null,
        permName: '',
        permUrl: '',
        permRemark: '',
        permType: '',
        permPid: 0,
    };

    // 如果传入了，就是添加的子级菜单，pid设置为传入的id
    //否则就是添加一级菜单，pid设置为0
    if (row) {
        console.log('添加子级菜单', row);
        form.value.permPid = row.permId;
        form.value.permType = row.permType;
    }
    showAddForm.value = true;
};

// 打开权限弹窗
const handleEdit = (row: any) => {
    form.value = {
        permId: row.permId,
        permName: row.permName,
        permUrl: row.permUrl,
        permRemark: row.permRemark,
        permType: row.permType,
        permPid: row.permPid,
    };
    showEditForm.value = true;
};


// 格式化时间的方法  去掉T
const formatTime = (time: string) => {
    if (!time) return '';
    return time.replace('T', ' ');
}

// 处理每页显示条数变化的事件
const handleSizeChange = (newPageSize: number) => {
    pageSize.value = newPageSize;
    permissionList();
};
// 处理当前页码变化的事件
const handleCurrentChange = (newPage: number) => {
    currentPage.value = newPage;
    permissionList();
};

// 新增权限
const handleAddSubmit = async () => {

        // 表单校验
    if (!form.value.permName) {
        ElMessage.error('权限名称不能为空');
        return;
    }
    if (!form.value.permUrl) {
        ElMessage.error('权限URL不能为空');
        return;
    }
    if (!form.value.permType) {
        ElMessage.error('权限类型不能为空');
        return;
    }
    if(!form.value.permRemark){
        ElMessage.error('权限备注不能为空');
        return;
    }



    try {
        // 调用新增接口
        const response = await addPermissionApi(form.value);
        console.log('新增权限', response);
        if (response.code === 200) {
            ElMessage.success('新增成功');
            // 刷新页面
            permissionList();
            // 关闭弹窗
            showAddForm.value = false;
        } else {
            ElMessage.error(response.msg);
        }
    } catch (error) {
        ElMessage.error('操作失败');
    }
};

// 修改权限
const handleEditSubmit = async () => {
    try {
        // 调用新增接口
        const response = await updatePermissionApi(form.value);
        console.log('修改权限', response);
        if (response.code === 200) {
            ElMessage.success('修改成功');
            // 刷新页面
            permissionList();
            // 关闭弹窗
            showEditForm.value = false;
        } else {
            ElMessage.error(response.msg);
        }
    } catch (error) {
        ElMessage.error('操作失败');
    }
};


// 删除权限
const handleDelete = async (id: number) => {
    ElMessageBox.confirm(
        '确认删除该权限?该操作会删除所有可能存在的子权限！',
        {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
        }
    ).then(async () => {
        try {
            // 调用删除接口
            const response = await deletePermissionApi(id);
            console.log('删除权限', response);
            if (response.code === 200) {
                ElMessage.success('删除成功');
                // 刷新页面
                permissionList();
            } else {
                ElMessage.error(response.msg);
            }
        } catch (error) {
            ElMessage.error('操作失败');
        }
    })
        // 取消
        .catch(() => {
            ElMessage.info('已取消');
        });
}

// 按钮权限列表
const buttonList=ref([]);
const hasDeleteButton = computed(() => {
  return buttonList.value.some(button => button === 'delete');
});


// 页面加载完后，加载默认数据
onMounted(() => {
    permissionList();
    const storedButtons = localStorage.getItem('buttonList');
  if (storedButtons) {
    buttonList.value = JSON.parse(storedButtons);
  }
});
// 表格行样式
const tableRowClassName = ({
  row,
  rowIndex,
}: {
  row: any
  rowIndex: number
}) => {
  row
  if (rowIndex%2 === 0) {
    return 'success-row'
  } 
  return ''
}

</script>
  
<style>
.el-table .warning-row {
  --el-table-tr-bg-color: var(--el-color-warning-light-9);
}
.el-table .success-row {
  --el-table-tr-bg-color: var(--el-color-success-light-9);
}
</style>
  